<!-- /@/components/Mapcontainer.vue -->
<template>
  <div id="container"></div>
</template>

<script setup lang="ts">
import { onMounted, watch, defineProps, defineEmits, ref } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'
import { ElMessage } from 'element-plus'

declare global {
  interface Window {
    _AMapSecurityConfig: any
  }
}

const props = defineProps({
  latitude: {
    type: Number,
    default: 39.90923
  },
  longitude: {
    type: Number,
    default: 116.397428
  }
})

const emit = defineEmits(['update:latitude', 'update:longitude', 'update:address'])

let map: any = null
let AMap: any = null
let marker: any = null
let geocoder: any = null
let placeSearch: any = null
let autoComplete: any = null

// 初始化地图
const initMap = async () => {
  window._AMapSecurityConfig = {
    securityJsCode: "c243f95c7b6503157150489e2206e17b",
  }

  try {
    AMap = await AMapLoader.load({
      key: '6df9de29656128c56fe25f6da02b9f5c',
      version: '2.0',
      plugins: ['AMap.AutoComplete', 'AMap.PlaceSearch', 'AMap.Geocoder']
    })
    const container = document.getElementById('container');
    if (!container) {
      console.error('未找到地图容器元素');
      return;
    }
    map = new AMap.Map('container', {
      zoom: 13,
      center: [props.longitude, props.latitude]
    })

    geocoder = new AMap.Geocoder()
    placeSearch = new AMap.PlaceSearch({ map: map })

    // 异步加载AutoComplete插件并处理相关逻辑
    await new Promise < void> ((resolve) => {
      AMap.plugin('AMap.AutoComplete', () => {
        autoComplete = new AMap.AutoComplete({
          input: "address_input",
          city: "全国",
          cityLimit: true,       // 限制只返回城市级结果
          type: "city|district|street"
        });

        // 监听输入框输入事件
        const inputElement = document.getElementById('address_input');
        if (inputElement) {
          inputElement.addEventListener('input', (e: any) => {
            const keyword = e.target.value;
            if (keyword) {
              autoComplete.search(keyword, (status: string, result: any) => {
                if (status === 'complete' && result && result.tips && result.tips.length > 0) {
                  console.log('输入提示内容:', result.tips);
                  // 可在此处根据需求处理提示数据，如显示下拉列表等
                }
              });
            }
          });
        }

        // 优化select事件处理
        autoComplete.on('select', (e: any) => {
          console.log(e)
          const poi = e.poi;
          if (!poi) {
            console.error('自动完成选择时未获取到有效的POI数据');
            ElMessage.error('请选择有效的地址');
            return;
          }
          console.log(poi);

          // 检查经纬度格式
          let location = poi.location;
          if (!location) {
            console.error('未获取到有效的经纬度位置信息');
            ElMessage.error('请输入具体地址');
            return;
          }

          // 处理经纬度数据
          let lng = location.lng;
          let lat = location.lat;
          console.log([lng, lat]);
          if (isNaN(lng) || isNaN(lat)) {
            console.error('经纬度转换失败:', location);
            ElMessage.error('经纬度解析失败');
            return;
          }
          updatePosition(lng, lat);
          emit('update:address', poi.name);
          ElMessage.success(`已选择: ${poi.name}`);
        });

        resolve();
      });
    });

    // 初始化标记
    updateMarker(props.longitude, props.latitude)
    // 绑定地图点击事件
    map.on('click', handleMapClick)
  } catch (error) {
    console.error('地图初始化失败:', error)
    ElMessage.error('地图加载失败，请稍后重试')
  }
}

// 处理地图点击
const handleMapClick = (e: any) => {
  const lnglat = e.lnglat
  updatePosition(lnglat.getLng(), lnglat.getLat())
  reverseGeocode(lnglat)
}

// 更新坐标
const updatePosition = (lng: number, lat: number) => {
  emit('update:longitude', lng)
  emit('update:latitude', lat)
  updateMarker(lng, lat)
}

// 更新标记
const updateMarker = (lng: number, lat: number) => {
  
  if (marker) {
    marker.setMap(null)
  }
  marker = new AMap.Marker({
    position: [lng, lat],
    map: map,
    title: '当前位置',
    draggable: true,  // 允许拖动标记
    cursor: 'move',
    raiseOnDrag: true
  })
  
  // 添加标记拖动事件处理
  marker.on('dragend', (e: any) => {
    const lnglat = e.lnglat;
    updatePosition(lnglat.getLng(), lnglat.getLat());
    reverseGeocode(lnglat);
  });
  map.setCenter([lng, lat])
  map.setZoom(15)  // 调整缩放级别，使位置更清晰
}

// 逆地理编码
const reverseGeocode = (lnglat: any) => {
  
  geocoder.getAddress(lnglat, (status: string, result: any) => {
    console.log(status);
    console.log(result);
    console.log('触发');
    if (status === 'complete' && result.info === 'OK') {
      emit('update:address', result.regeocode.formattedAddress)
    } else {
      console.error('逆地理编码失败:', status, result)
      ElMessage.warning('无法获取当前位置的地址信息')
    }
  })
}

// 暴露给父组件的方法
const searchByKeyword = (keyword: string) => {
  if (!keyword) return;

  placeSearch.search(keyword, (status: string, result: any) => {
    if (status === 'complete' && result.pois?.length) {
      const poi = result.pois[0]
      const [lng, lat] = poi.location.split(',').map(Number)
      updatePosition(lng, lat)
      emit('update:address', poi.name)
      ElMessage.success(`找到位置: ${poi.name}`)
    } else {
      ElMessage.warning('未找到相关位置信息')
    }
  })
}

// 监听props变化
watch(() => [props.latitude, props.longitude], ([newLat, newLng]) => {
  if (map && newLat && newLng) {
    map.setCenter([newLng, newLat])
    updateMarker(newLng, newLat)
  }
})

onMounted(initMap)

defineExpose({
  searchByKeyword
})
</script>

<style scoped>
#container {
  width: 100%;
  height: 400px;
  margin: 20px auto;
  border: 1px solid #ddd;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
</style>